package util.fileChooser;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.border.BevelBorder;

public class PanelVistaPrevia extends JComponent implements PropertyChangeListener{

  
  ImageIcon imagenIcon = null; 
    
   public PanelVistaPrevia(JFileChooser fileChooser) { 
	setPreferredSize(new Dimension(240,180)); 
	fileChooser.addPropertyChangeListener(this); 
	setBorder(new BevelBorder(BevelBorder.LOWERED)); 
   } 
    
   public void loadImage(File file) { 
       if (file == null) { 
    	   imagenIcon = null; 
       } else { 
	    ImageIcon tmpIcon = new ImageIcon(file.getPath()); 
	    if(tmpIcon.getIconWidth() > 240 || tmpIcon.getIconWidth() < 240 ) { 
	    	imagenIcon = new ImageIcon( 
		    tmpIcon.getImage().getScaledInstance(240, 180, Image.SCALE_DEFAULT)); 
	    } else { 
	    	imagenIcon = tmpIcon; 
	    }
	} 
   } 
 
   
    
   public void paint(Graphics g) { 
	super.paint(g); 
	if(imagenIcon != null) { 
	    int x = getWidth()/2 - imagenIcon.getIconWidth()/2; 
	    int y = getHeight()/2 - imagenIcon.getIconHeight()/2; 
	    if(y < 0) { 
		y = 0; 
	    } 
	     
	    if(x < 5) { 
		x = 5; 
	    } 
	    imagenIcon.paintIcon(this, g, 0, 0); 
	} 
   }

	@Override
	public void propertyChange(PropertyChangeEvent e) {
		String prop = e.getPropertyName(); 
		if(prop == JFileChooser.SELECTED_FILE_CHANGED_PROPERTY) { 
		    if(isShowing()) { 
	               loadImage((File) e.getNewValue()); 
			repaint(); 
		    } 
		} 
	} 
}

